package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 角色业务层
 *
 * @author 杨兴健
 * @Date 2020/7/9 10:34
 */
@Service
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper mapper;


    /**
     * 根据条件查询角色并封装成ResultSet对象
     *
     * @param qo
     * @return
     */
    @Override
    public PageInfo<Role> selectAllByQO(QueryObject qo) {
//        用PageHelper插件开始分页
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = mapper.selectAllByQO(qo);

        return new PageInfo<Role>(roles);
    }


    /**
     * 根据id查询角色
     *
     * @param id
     * @return
     */
    @Override
    public Role selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    /**
     * 跟新角色和角色关联的权限
     *
     * @param role
     * @param pids
     */
    @Override
    public void update(Role role, Long[] pids) {

        mapper.updateByPrimaryKey(role);
        mapper.deleteRelation(role.getId());
        if (pids != null && pids.length > 0) {
            for (Long pid : pids) {
                mapper.insertRelation(role.getId(), pid);
            }
        }


    }

    /**
     * 添加角色和角色关联的权限
     */

    @Override
    public void insert(Role role, Long[] pids) {
        mapper.insert(role);
        if (pids != null && pids.length > 0) {
            for (Long pid : pids) {
                mapper.insertRelation(role.getId(), pid);
            }
        }
    }

    /**
     * 根据id删除角色
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询所有角色
     *
     * @return
     */
    @Override
    public List<Role> selectAll() {

        return mapper.selectAll();
    }


    /**
     * 添加或更新角色
     *
     * @param role
     * @param pids
     */
    @Override
    public void saveOrUpdate(Role role, Long[] pids) {
        if (role == null) {
            throw new RuntimeException("数据为空");
        }
        if (role.getId() != null) {
            mapper.deleteRelation(role.getId());
            mapper.updateByPrimaryKey(role);
        } else {
            mapper.insert(role);
        }
        if (pids != null && pids.length > 0) {
            for (Long pid : pids) {
                mapper.insertRelation(role.getId(), pid);
            }
        }
    }
}
